from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.db import transaction
from bs4 import BeautifulSoup
from common.pagination import PageQuerySet
from common.logger import log
from user.models import User
from home import models


@login_required
def mysite(request, username, **kwargs):
    '''博客个人主页'''

    user_obj = User.objects.filter(username= username).first()
    blog_obj = models.Blog.objects.filter(user=user_obj).first()

    article_list = models.Article.objects.filter(blog= blog_obj)

    # 分页
    obj = PageQuerySet(request, article_list)
    page_queryset, page_obj = obj.get_page_queryset()

    return render(request, 'mysite/mysite.html',
                  {'user_obj': user_obj,
                   'blog_obj': blog_obj,
                   'page_queryset': page_queryset,
                   'page_obj': page_obj})



class PublishedArticle(View):
    '''发布文章'''
    def __init__(self):
        self.title = None
        self.content = None
        self.type = None
        self.category = None
        self.tag_list = None
        self.desc = None

    @method_decorator(login_required)
    def get(self, request):
        tag_list = models.Tag.objects.all()
        category_list = models.Category.objects.all()

        return render(request, 'mysite/publish_article.html',
                      {'tag_list': tag_list,
                       'category_list': category_list}
                      )

    def post(self, request):
        self.title = request.POST.get('title')
        self.content = request.POST.get('content')
        self.type = request.POST.get('type')
        self.category = request.POST.get('category')
        self.tag_list = request.POST.getlist('tag')

        self._deal_content()
        self._deal_type()

        blog = models.Blog.objects.filter(
            user = request.user
            ).first()


        try:
            with transaction.atomic():
                # 修改数据库
                article_obj = models.Article.objects.create(
                    title=self.title,
                    desc=self.desc,
                    type=self.type,
                    content=self.content,
                    blog=blog,
                    category_id=self.category
                )

                # 操作文章与标签第三张表
                article_obj_list = []
                for i in self.tag_list:
                    tag_article_obj = models.Article2Tag(
                        article=article_obj,
                        tag_id=i
                    )
                    article_obj_list.append(tag_article_obj)
                # bulk_create批量创建tag对象数据
                models.Article2Tag.objects.bulk_create(article_obj_list)

        except Exception as e:
            log.error('数据库创建文章数据失败', e)

        return redirect(f'/mysite/{request.user}/')

    def _deal_content(self):
        '''过滤文章中的script等脚本语言'''

        soup = BeautifulSoup(self.content, 'html.parser')
        print(soup.prettify())
        # 拿到文章中的所有标签（html、script等）
        tags =soup.find_all()

        for tag in tags:
            # 删除script标签
            if tag.name == 'extra':
                tag.decompose()

        # 文章简介
        self.desc = soup.text[0:150]
        self.content = str(soup)

    def _deal_type(self):
        '''获取文章发布类型'''
        if self.type == 'original':
            self.type = '0'
        else:
            self.type = '转载'
